package baseFx.springboot;

import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class FxMvcConfig implements WebMvcConfigurer, WebMvcRegistrations {
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/fx/**").addResourceLocations("classpath:/fxstatic/");
    }

    /**
     * 跨域设置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*");
    }

    /**
     * URL忽略大小写
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher matcher = new AntPathMatcher();
        matcher.setCaseSensitive(false);
        configurer.setPathMatcher(matcher);
    }

    /**
     * handler事件触发器
     */
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        if (requestMappingHandlerMapping == null) {
            requestMappingHandlerMapping = createRequestMappingHandlerMapping();
        }
        return requestMappingHandlerMapping;
    }

    protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
        return new FxRequestMappingHandler();
    }

    /**
     * action事件触发器
     */
    @Override
    public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
        if (requestMappingHandlerAdapter == null) {
            requestMappingHandlerAdapter = createRequestMappingHandlerAdapter();
        }
        return requestMappingHandlerAdapter;
    }

    protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
        return new FxRequestMappingHandlerAdapter();
    }

    /**
     * request事件触发器
     */
    @Bean
    public ServletListenerRegistrationBean<FxRequestListener> requestContextListener(MvcEvents mvcEvents) {
        return new ServletListenerRegistrationBean<>(new FxRequestListener(mvcEvents));
    }
}
